package com.wty.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author wangtengyu
 * @Create 2018-05-16-10:52
 */
@Slf4j
public  class SynchronizedExample1 {

    //修饰代码块
    public void test1(int j) {
        synchronized (this) {
            for (int i = 1; i <= 10; i++) {
                log.info("test{}-{}", j, i);
            }
        }
    }

    //修饰一个方法
    public synchronized void test2(int j) {
        for (int i = 1; i <= 10; i++) {
            log.info("test{}-{}", j, i);
        }
    }

    //修饰一个静态方法
    public static synchronized void test3(int j) {
        for (int i = 1; i <= 10; i++) {
            log.info("test{}-{}", j, i);
        }
    }

    //修饰一个类
    public  void test4(int j) {
        synchronized (SynchronizedExample1.class){
            for (int i = 1; i <= 10; i++) {
                log.info("test{}-{}", j, i);
            }
        }
    }

    //测试一个对象有多个synchronized方法，当有一个被访问时其他线程不能访问其他的synchronized方法
    public synchronized void test5(int j){
        for (int i = 1; i <= 10; i++) {
            log.info("for test{}-{}", j, i);
        }
    }

    public static void main(String[] args) {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2=new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            example1.test4(1);
        });
        executorService.execute(() -> {
            example2.test4(2);
        });
    }


}
